package com.threader.ui;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import javax.swing.table.AbstractTableModel;

import com.threader.bo.People;
import com.threader.utils.ConstantRegistry;


public class PeoplesTableModel extends AbstractTableModel implements Observer {
	private static final long serialVersionUID = 7265543035716447642L;
	private final String[] columnNames = { "Name", "Status", "Schedule", "Health", "Hungry", "Money"};
	@SuppressWarnings({ "rawtypes" })
	private final Class[] columnClasses = { String.class, String.class, String.class, String.class, String.class, String.class};

	ArrayList<People> peoplesList = new ArrayList<People>();

	public PeoplesTableModel(){
		super();
	}
	
	public Object getValueAt(int row, int col) {
	    People people = peoplesList.get(row);
	    switch (col) {
	    case 0: // Name
	    	return people;
	    case 1: // Status
	    	return people.getStateName();
	    case 2: // Schedule
	    	if(people.getPost()!=null){
	    		int endWorck = people.getWorckBeginTimeHour()+ConstantRegistry.worckDayLength+ConstantRegistry.dinnerLength;
	    		if(endWorck>23)
	    			endWorck = endWorck - 24;
	    		return String.format("%02d", people.getWorckBeginTimeHour())+":"+String.format("%02d", people.getWorckBeginTimeMinute()) + " - " + String.format("%02d", endWorck)+":"+String.format("%02d", people.getWorckBeginTimeMinute());
	    	} else return "";
	    case 3: // Helth
	    	return new BigDecimal(people.getHelth()).setScale(0, BigDecimal.ROUND_HALF_UP)+"%";
	    case 4: // Hungry
	    	return new BigDecimal(people.getEat()).setScale(0, BigDecimal.ROUND_HALF_UP)+"%"; 
	    case 5: // Money
	    	return "$"+people.getMoney(); 
	    default: return "";
	    }
	}

	public void addPeople(People p) {
		p.addObserver(this);
		peoplesList.add(p);
		fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
	}

	public void delPeople(int row) {
		peoplesList.get(row).deleteObserver(this);
		peoplesList.remove(row);
		fireTableRowsDeleted(row, row);
	}
	
	public People getPeople(int row) {
		return peoplesList.get(row);
	}		

	public int getColumnCount() {
		return columnNames.length;
	}

	public int getRowCount() {
		return peoplesList.size();
	}

	public String getColumnName(int col) {
		return columnNames[col];
	}

	public Class<?> getColumnClass(int col) {
		return columnClasses[col];
	}
	
	public void update(Observable o, Object arg) {
		int index = peoplesList.indexOf(o);
		fireTableRowsUpdated(index, index);
	}
}
